//
//  Organized_systemViewController.m
//  fxxiaoke
//
//  Created by 鞠超 on 16/9/17.
//  Copyright © 2016年 jc. All rights reserved.
//

#import "Organized_systemViewController.h"

#import "Organization_FrameTableViewCell.h"
#import "Select_DirectlyleaderTableViewCell.h"
#import "Select_scopeViewController.h"

@interface Organized_systemViewController () <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchControllerDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) UITableView * tableView;
//全选
@property (nonatomic, strong) UIButton * btn_selectAll;

@property (nonatomic, strong) UIView * view_Head;
//搜索框
@property (nonatomic, strong) UISearchController * searchController;

@property (nonatomic, strong) UIView * view_Bottom;
@property (nonatomic, strong) UIButton * btn_Company;
@property (nonatomic, strong) UILabel * lbl_rightGrade;
@property (nonatomic, strong) UIButton * btn_Department;

//底部视图
@property (nonatomic, strong) UIView * view_bottom;
@property (nonatomic, strong) UILabel * lbl_selected;
@property (nonatomic, strong) UIButton * btn_BottomDepartment;
@property (nonatomic, strong) UIButton * btn_define;

//数据
@property (nonatomic, assign) NSInteger data_number;
//状态
@property (nonatomic, assign) BOOL is_user;

@end

@implementation Organized_systemViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self p_navi];
    
    [self p_setupView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - navi
- (void )p_navi
{
    _btnLeft.hidden = YES;
    _lblLeft.hidden = YES;
    _btnRight.hidden = YES;
    _lblRight.hidden = YES;
    
    _lblTitle.text = @"按组织架构查看";
    
    //左返回
    UIImageView * image_LeftRetrun = [[UIImageView alloc] initWithFrame:CGRectMake(8, 31.5, 25, 25)];
    image_LeftRetrun.userInteractionEnabled = YES;
    image_LeftRetrun.image = [UIImage imageNamed:@"Left-return.png"];
    [_topView addSubview:image_LeftRetrun];
    
    UILabel * lbl_return = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(image_LeftRetrun.frame) - 6, 35, 95, 15)];
    lbl_return.text = @"选择直属上级";
    lbl_return.textColor = [UIColor whiteColor];
    lbl_return.font = [UIFont systemFontOfSize:15];
    [_topView addSubview:lbl_return];
    //分开适配
    if(SCREEN_WIDTH == 320)
    {
        lbl_return.text = @"返回";
        lbl_return.frame = CGRectMake(CGRectGetMaxX(image_LeftRetrun.frame) - 6, 35, 40, 15);
    }
    
    UIButton * btn_return = [UIButton buttonWithType:(UIButtonTypeSystem)];
    btn_return.frame = CGRectMake(7, 22, 20 + lbl_return.frame.size.width, 40);
    [_topView addSubview:btn_return];
    [btn_return addTarget:self action:@selector(btn_returnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    //右全选
    self.btn_selectAll = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.btn_selectAll.frame = CGRectMake(SCREEN_WIDTH - 5 - 50, 20 + 7, 50, 30);
    [self.btn_selectAll setTitle:@"全选" forState:(UIControlStateNormal)];
    [self.btn_selectAll setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    self.btn_selectAll.titleLabel.font = [UIFont systemFontOfSize:17];
    [_topView addSubview:self.btn_selectAll];
    [self.btn_selectAll addTarget:self action:@selector(btn_selectAllAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.btn_selectAll.hidden = YES;
}

//左返回
- (void )btn_returnAction:(UIButton *)sender
{
    //取消活跃状态
    self.searchController.active = 0;
    
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

//全选
- (void )btn_selectAllAction:(UIButton *)sender
{
    NSLog(@"全部选中");
}

//tabbar
- (void )viewWillAppear:(BOOL)animated
{
    [(AppDelegate *)[[UIApplication sharedApplication] delegate] hiddenTabBar];
}

#pragma mark - 布局
- (void )p_setupView
{
    self.data_number = 5;
    
    self.view.backgroundColor = [UIColor whiteColor];
    //底部视图
    [self p_BottomView];
    //头视图
    [self p_headView];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view_Head.frame), SCREEN_WIDTH, SCREEN_HEIGHT - CGRectGetMaxY(self.view_Head.frame) - 40) style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.tableView];
    
    //注册
    [self.tableView registerClass:[Organization_FrameTableViewCell class] forCellReuseIdentifier:@"cell_department"];
    
    //注册_user
    [self.tableView registerClass:[Select_DirectlyleaderTableViewCell class] forCellReuseIdentifier:@"cell_UserList"];
}

#pragma mark - tableview代理
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data_number;
}

- (CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0f;
}

- (UITableViewCell * )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.searchController.active == 0)
    {
        if(self.is_user == 0)
        {
            Organization_FrameTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell_department" forIndexPath:indexPath];
            cell.name_department.text = [NSString stringWithFormat:@"销售%ld部",indexPath.row + 1];
            cell.department_number.text = [NSString stringWithFormat:@"%ld人",indexPath.row + 5];
            
            return cell;
        }
        else
        {
            Select_DirectlyleaderTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell_UserList" forIndexPath:indexPath];
            cell.btn_Select.userInteractionEnabled = NO;
            
            cell.image_Head.image = [UIImage imageNamed:@"heads.jpg"];
            cell.user_Name.text = @"XXX(姓名)";
            cell.user_Department.text = @"销售经理-XX销售X部";
            
            return cell;
        }
    }
    else
    {
        Select_DirectlyleaderTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell_UserList" forIndexPath:indexPath];
        cell.btn_Select.userInteractionEnabled = NO;
        
        cell.image_Head.image = [UIImage imageNamed:@"heads.jpg"];
        cell.user_Name.text = @"XXX(姓名)";
        cell.user_Department.text = @"销售经理-XX销售X部";
        
        return cell;
    }
}

- (void )tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(self.searchController.active == 1)
    {NSLog(@"点击保存数据,刷新底部视图");
        
//        [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        if(self.is_user == 0)
        {
            self.btn_selectAll.hidden = NO;

            self.is_user = 1;
            
            [self p_setupView];
            
            self.data_number = 5 + indexPath.row;
            [self.btn_Company setTitleColor:[UIColor orangeColor] forState:(UIControlStateNormal)];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //刷新tableView(记住,要更新放在主线程中)
                [self.tableView reloadData];
            });
        }
        else
        {NSLog(@"点击保存数据,刷新底部视图");
            
//            [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        }
    }
}

#pragma mark - 点击全公司后返回首层
- (void )btn_CompanyAction:(UIButton *)sender
{
    if(![sender.titleLabel.textColor isEqual:[UIColor grayColor]])
    {//        NSLog(@"点击全公司后返回首层");
        self.btn_selectAll.hidden = YES;

        self.is_user = 0;
        
        [self p_setupView];
        
        self.data_number = 5;
        [self.btn_Company setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //刷新tableView(记住,要更新放在主线程中)
            [self.tableView reloadData];
        });
    }
}

#pragma mark - 头视图
- (void )p_headView
{
    if(self.searchController.active == 0)
    {
        self.view_Head = [[UIView alloc] init];
        self.view_Head.frame = CGRectMake(0, 64, SCREEN_WIDTH, 84);
        self.view_Head.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [self.view addSubview:self.view_Head];
        
        //搜索栏
        self.searchController.searchBar.frame = CGRectMake(0, 0, SCREEN_WIDTH, 44);
        self.searchController.searchBar.placeholder = @"搜姓名、手机号";
        self.searchController.dimsBackgroundDuringPresentation = NO;
        self.searchController.searchResultsUpdater = self;
        self.searchController.delegate = self;
        [self.view_Head addSubview:self.searchController.searchBar];
        
        self.view_Bottom = [[UIView alloc] initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH, 40)];
        self.view_Bottom.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [self.view_Head addSubview:self.view_Bottom];
        //全公司
        CGFloat lengt_x = [self buttonWidthWithText:@"全公司"];
        self.btn_Company = [UIButton buttonWithType:(UIButtonTypeCustom)];
        self.btn_Company.frame = CGRectMake(10, 5, lengt_x, 30);
        [self.btn_Company setTitle:@"全公司" forState:(UIControlStateNormal)];
        [self.btn_Company setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        self.btn_Company.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.view_Bottom addSubview:self.btn_Company];
        [self.btn_Company addTarget:self action:@selector(btn_CompanyAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
        //成员列表页面
        if(self.is_user == 1)
        {
            [self.btn_Company setTitleColor:[UIColor orangeColor] forState:(UIControlStateNormal)];
            
            self.lbl_rightGrade = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.btn_Company.frame) + 7, 12, 15, 15)];
            self.lbl_rightGrade.text = @">";
            self.lbl_rightGrade.textColor = [UIColor grayColor];
            self.lbl_rightGrade.font = [UIFont systemFontOfSize:15];
            [self.view_Bottom addSubview:self.lbl_rightGrade];
            
            CGFloat lengt_x1 = [self buttonWidthWithText:@"销售X部"];
            self.btn_Department = [UIButton buttonWithType:(UIButtonTypeCustom)];
            self.btn_Department.frame = CGRectMake(CGRectGetMaxX(self.lbl_rightGrade.frame) + 7, 5, lengt_x1, 30);
            [self.btn_Department setTitle:@"销售X部" forState:(UIControlStateNormal)];
            [self.btn_Department setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
            self.btn_Department.titleLabel.font = [UIFont systemFontOfSize:15];
            [self.view_Bottom addSubview:self.btn_Department];
        }
        else
        {
            self.lbl_rightGrade.hidden = YES;
            self.btn_Department.hidden = YES;
        }
    }
    else
    {
        self.view_Head = [[UIView alloc] init];
        self.view_Head.frame = CGRectMake(0, 64, SCREEN_WIDTH, 44);
        self.view_Head.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [self.view addSubview:self.view_Head];
        
        //搜索栏
        self.searchController.searchBar.frame = CGRectMake(0, 0, SCREEN_WIDTH, 44);
        self.searchController.searchBar.placeholder = @"搜姓名、手机号";
        self.searchController.dimsBackgroundDuringPresentation = NO;
        self.searchController.searchResultsUpdater = self;
        self.searchController.delegate = self;
        [self.view_Head addSubview:self.searchController.searchBar];
    }
}

#pragma mark - UISearchController代理和update
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    if([searchController.searchBar.text length] > 0)
    {
        self.data_number = 2;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //刷新tableView(记住,要更新放在主线程中)
            [self.tableView reloadData];
        });
    }
}

- (void)didPresentSearchController:(UISearchController *)searchController
{
    self.btn_selectAll.hidden = NO;

    [self p_setupView];
    
    self.data_number = 0;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        //刷新tableView(记住,要更新放在主线程中)
        [self.tableView reloadData];
    });
}

- (void)didDismissSearchController:(UISearchController *)searchController
{
    self.btn_selectAll.hidden = YES;

    [self p_setupView];
    
    self.data_number = 5;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        //刷新tableView(记住,要更新放在主线程中)
        [self.tableView reloadData];
    });
}


#pragma mark - scrollView代理
- (void )scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if(self.searchController.active == 1)
    {
        [self.searchController.searchBar endEditing:YES];
    }
}

#pragma mark - 懒加载搜索框控制器
- (UISearchController *)searchController
{
    if(_searchController == nil)
    {
        self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    }
    
    return _searchController;
}

#pragma 自定义宽度
- (CGFloat )buttonWidthWithText:(NSString * )string
{
    CGFloat length_W = [string boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, 30)    options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]} context:nil].size.width;
    
    return length_W;
}

#pragma mark - 底部视图
- (void )p_BottomView
{
    self.view_Bottom = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40)];
    self.view_Bottom.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.view_Bottom];
    
    UIView * view_bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.30)];
    view_bottomLine.backgroundColor = [UIColor grayColor];
    [self.view_Bottom addSubview:view_bottomLine];
    
    //确定
    self.btn_define = [UIButton buttonWithType:(UIButtonTypeSystem)];
    self.btn_define.frame = CGRectMake(SCREEN_WIDTH - 80 - 5, 5, 80, 30);
    self.btn_define.backgroundColor = [UIColor colorWithRed:250/255.0 green:176/255.0 blue:96/255.0 alpha:1.0f];
    self.btn_define.layer.cornerRadius = 5;
    [self.btn_define setTitle:@"确定" forState:(UIControlStateNormal)];
    [self.btn_define setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [self.view_Bottom addSubview:self.btn_define];
    [self.btn_define addTarget:self action:@selector(btn_defineAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    //已选择
    self.lbl_selected = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 55, 20)];
    self.lbl_selected.text = @"已选择:";
    self.lbl_selected.font = [UIFont systemFontOfSize:15.0f];
    self.lbl_selected.textColor = [UIColor colorWithRed:250/255.0 green:176/255.0 blue:96/255.0 alpha:1.0f];
    [self.view_Bottom addSubview:self.lbl_selected];
    
    //点击后部门及同事
    self.btn_BottomDepartment = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.btn_BottomDepartment.frame = CGRectMake(CGRectGetMaxX(self.lbl_selected.frame) + 5, 5, SCREEN_WIDTH - CGRectGetMaxX(self.lbl_selected.frame) - 95, 30);
    [self.btn_BottomDepartment setTitleColor:[UIColor colorWithRed:250/255.0 green:176/255.0 blue:96/255.0 alpha:1.0f] forState:(UIControlStateNormal)];
    [self.btn_BottomDepartment setTitle:@"销售中心,XXX" forState:(UIControlStateNormal)];
    //文字靠在显示 *************************************************************
    self.btn_BottomDepartment.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    self.btn_BottomDepartment.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    self.btn_BottomDepartment.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [self.view_Bottom addSubview:self.btn_BottomDepartment];
    [self.btn_BottomDepartment addTarget:self action:@selector(btn_BottomDepartmentAction:) forControlEvents:(UIControlEventTouchUpInside)];
}

#pragma mark - 点击确定
- (void )btn_defineAction:(UIButton *)sender
{//    NSLog(@"点击确定");
    
    NSUserDefaults * userdefault = [NSUserDefaults standardUserDefaults];
    [userdefault setObject:@"3" forKey:@"record_Rows"];
    
    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 点击后部门及同事
- (void )btn_BottomDepartmentAction:(UIButton *)sender
{
//    NSLog(@"点击后模态出部门及同事");
    
    Select_scopeViewController * select_scopeViewController = [[Select_scopeViewController alloc] init];
    [self presentViewController:select_scopeViewController animated:YES completion:^{
    }];
}














@end
